package com.headwind.logistics.permission.controller;

import com.headwind.logistics.common.constant.UserSessionKey;
import com.headwind.logistics.common.util.Md5Util;
import com.headwind.logistics.common.pojo.Employee;
import com.headwind.logistics.common.util.RedisUtils;
import com.headwind.logistics.log.annotate.Log;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台登录控制器
 */
@Controller
public class LoginController {

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 后台员工登录方法
     * @return
     */
    @RequestMapping(value = "adminLogin",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> adminLogin(Employee employee,boolean rememberMe, HttpSession session){

        Map<String,Object> map = new HashMap<>();

        //传来的密码加密
        String md5Password = Md5Util.getMD5(employee.getPassword());

        //把加密的密码再次 赋值到 user对象
        employee.setPassword(md5Password);

        //1、获取 Subject
        Subject subject = SecurityUtils.getSubject();
        //2、封装用户数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(employee.getEmployeeNo(), employee.getPassword(),rememberMe);

        //3、执行登录方法
        try {

            subject.login(usernamePasswordToken);
            //获取用户对象
            Employee emp = (Employee)subject.getPrincipal();
            session.setAttribute("EMPLOYEE",emp);

            //把员工id放入redis缓存中
            redisUtils.hmSet("EMPLOYEEID","EMPLOYEE",emp.getEmployeeId());

            map.put("code",200);

        } catch (UnknownAccountException e) {//该异常用户名称不存在

            //登录失败，用户名称不存在
            map.put("code",400);

        } catch (IncorrectCredentialsException e) {//该异常密码错误
            //登录失败，密码错误
            map.put("code",400);
        }


        return map;
    }

    /**
     * 退出登录
     * @param response
     * @return
     */
    @RequestMapping("/admin/logout")
    public String logout(HttpServletResponse response) {
        Subject lvSubject=SecurityUtils.getSubject();
        lvSubject.logout();
        response.setStatus(302);

        return "/admin/login";
    }

}
